package com.fy56.platform.logistics.service.impl;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fy56.platform.logistics.common.ResultModel;
import com.fy56.platform.logistics.common.ResultStatus;
import com.fy56.platform.logistics.mapper.CompanyMapper;
import com.fy56.platform.logistics.mapper.DeliverGoodsWebSetMapper;
import com.fy56.platform.logistics.mapper.UserCompanyMapper;
import com.fy56.platform.logistics.model.Company;
import com.fy56.platform.logistics.model.DeliverGoodsWeb;
import com.fy56.platform.logistics.model.UserCompany;
import com.fy56.platform.logistics.service.wx.ICompanyInfoService;
import com.fy56.platform.logistics.utils.*;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zeus.base.privilege.model.TbCompany;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import static com.fy56.platform.logistics.utils.HttpUtil.setHeader;

/**
 * Created by Edwin Yang on 2018/2/28 0028.
 */
@Service
public class CompanyInfoServiceImpl implements ICompanyInfoService {
    private static Logger log = Logger.getLogger(CompanyInfoServiceImpl.class);
    @Autowired
    private CompanyMapper companyMapper;

    @Autowired
    private UserCompanyMapper userCompanyMapper;


    @Autowired
    private DeliverGoodsWebSetMapper deliverGoodsWebSetMapper;

    @Override
    public Company selectByPrimaryKey(Long id) {
        return companyMapper.selectByPrimaryKey(id);
    }

    @Override
    public Company getCompanyById(Long id) {
        return companyMapper.selectById(id);
    }

    @Override
    @Transactional(readOnly = false)
    public ResultModel updateCompany(Company entity) {
        ResultModel result = null;
        int r = companyMapper.updateCompanySelective(entity);
        if (r == 0) {
            result = new ResultModel(ResultStatus.EDIT_ERR);
        } else {
            result = ResultModel.ok();
        }
        return result;
    }

    @Override
    public List<Company> getCompanyListByUserId(Company entity) {
        return companyMapper.getCompanyListByUserId(entity);
    }

    /**
     * 获取从认证中心获取所有子公司信息
     *
     * @param code
     * @return
     */
    @Override
    public List<Company> getWebList(String code, String longitude, String latitude,Company model) {
//        String result = "";
        if(model==null){
            model = companyMapper.selectByCode(code);
        }
//        if(model == null || StringUtil.isEmpty(model.getUrl())){
//            throw new NullPointerException("未设置企业URL地址");
//        }
//        String url = model.getUrl() + "/orderBaseInfo/getWebList";
//        if(StringUtil.isNotEmpty(model.getF6AccountSet()) && StringUtil.isNotEmpty(model.getF6OrganizationCode())){
//            url += "?accountName=" + model.getF6AccountSet() + "&organizationCode=" + model.getF6OrganizationCode();
//        }
//        result = HttpUtil.get(url);

        //初始化返回值
        List<Company> list = Lists.newArrayList();
        List<TbCompany> subCompanyList = new ArrayList<TbCompany>();

        //查出本地数据库（后期改为不查本地 直接查腾云）
       /* DeliverGoodsWeb childParam = new DeliverGoodsWeb();
        childParam.setParentCode(code);
        childParam.setDeleteFlag(0);
        List<DeliverGoodsWeb> resChildList = deliverGoodsWebSetMapper.select(childParam);
        if (resChildList != null && resChildList.size() > 0) {
            for (DeliverGoodsWeb web : resChildList) {
                subCompanyList.add(deliverGoodsWebToTbCompany(web));
            }
        } else {*/
            //获取从认证中心获取所有子公司信息
//            subCompanyList = iCompanyService.selectByParentId(Integer.valueOf(String.valueOf(model.getId())));
            //20200414 lml 改成http方式请求腾云获取公司信息
            try {
                Long begin = System.currentTimeMillis();//开始时间
                Map<String, String> paramsNew = Maps.newHashMap();
                paramsNew.put("companyCode", model.getCode());
                paramsNew.put("passWord", MD5Util.getMD5Code(model.getTenantPass()));
                paramsNew.put("parentId", model.getId() + "");
                String result = HttpClientUtils.post(StaticUtil.restSearchURL + "/privilegeManager/selectByParentId", paramsNew, setHeader(), 20000, 20000);
                Long end = System.currentTimeMillis();//结束时间
                log.info("getOrderBaseInfo 腾云获取网点:" + (end - begin) + "毫秒。");
                if (result != null) {
                    JSONObject j = JSON.parseObject(result);
                    String object = j.get("object") + "";
                    subCompanyList = JSON.parseArray(object, TbCompany.class);
                }
            } catch (Exception e) {
                System.out.println(e);
            }

//        }

        Long begin = System.currentTimeMillis();//开始时间
        //构筑网点信息（名称，地址，距我，经度，纬度）
        if (CollectionUtils.isNotEmpty(subCompanyList)) {
            Company company = null;
            for (TbCompany web : subCompanyList) {
                if (web.getDisplayFlag() != 1) {
                    company = new Company();
                    company.setName(web.getCompanyNameAlias() != null ? web.getCompanyNameAlias() : web.getCompanyName());
                    company.setAddress(web.getAddressMap() != null ? web.getAddressMap() : web.getAddress());
                    company.setPhone(web.getPhone());
                    if (web.getLongitude() != null && web.getLatitude() != null) {
                        //百度地图坐标转换成腾讯地图坐标
                        double pi = 3.141592653589793 * 3000.0 / 180.0;
                        double x = web.getLongitude() - 0.0065, y = web.getLatitude() - 0.006;
                        double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * pi);
                        double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * pi);
                        double gg_lon = z * Math.cos(theta);
                        double gg_lat = z * Math.sin(theta);
                        web.setLongitude(gg_lon);
                        web.setLatitude(gg_lat);

                        if (StringUtil.isNotEmpty(longitude) && StringUtil.isNotEmpty(latitude)) {
//                            double x1 = Double.valueOf(longitude) - 0.0065, y1 = Double.valueOf(latitude) - 0.006;
//                            double z1 = Math.sqrt(x1 * x1 + y1 * y1) - 0.00002 * Math.sin(y1 * pi);
//                            double theta1 = Math.atan2(y1, x1) - 0.000003 * Math.cos(x1 * pi);
//                            double gg_lon1 = z1 * Math.cos(theta1);
//                            double gg_lat1 = z1 * Math.sin(theta1);
                            company.setDistance(GoogleMapHelper.getDistance(Double.valueOf(longitude), Double.valueOf(latitude), web.getLongitude(), web.getLatitude()));
                        }
                        company.setLatitude(web.getLatitude());
                        company.setLongitude(web.getLongitude());
                    }
                    list.add(company);
                }
            }
        }

        //重新排序并得到最新的10条记录
        if (list.size() > 0) {
            sort(list);
        }
        Long end = System.currentTimeMillis();//结束时间
        log.info("getOrderBaseInfo 网点坐标排序:" + (end - begin) + "毫秒。");
        return list;
    }

    @Override
    public ResultModel getWebListById(String code, String longitude, String latitude, String administrativeDivisionCode, String wdName) {
        Company model = companyMapper.selectByCode(code);
        ResultModel resultModel = new ResultModel(ResultStatus.SUCCESS , "操作成功");
        //初始化返回值
        List<Company> list = Lists.newArrayList();
        List<TbCompany> subCompanyList = new ArrayList<TbCompany>();

        //获取从认证中心获取所有子公司信息
        //20200414 lml 改成http方式请求腾云获取公司信息
        try {
            Map<String, String> paramsNew = Maps.newHashMap();
            paramsNew.put("companyCode", model.getCode());
            paramsNew.put("administrativeDivisionCode", administrativeDivisionCode);
            paramsNew.put("wdName", wdName);
            paramsNew.put("parentId", model.getId() + "");
            String result = HttpClientUtils.post(StaticUtil.restSearchURL + "/privilegeManager/selectByDivisionId", paramsNew, null, 20000, 20000);
            if (result != null) {
                JSONObject j = JSON.parseObject(result);
                String object = j.get("object") + "";
                subCompanyList = JSON.parseArray(object, TbCompany.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultModel(ResultStatus.SERVER_ERROR , "服务端失败");
        }

        //构筑网点信息（名称，地址，距我，经度，纬度）
        if (CollectionUtils.isNotEmpty(subCompanyList)) {
            Company company = null;
            for (TbCompany web : subCompanyList) {
                if (web.getDisplayFlag() != 1) {
                    company = new Company();
                    company.setName(web.getCompanyNameAlias() != null ? web.getCompanyNameAlias() : web.getCompanyName());
                    company.setAddress(web.getAddressMap() != null ? web.getAddressMap() : web.getAddress());
                    company.setPhone(web.getPhone());
                    if (web.getLongitude() != null && web.getLatitude() != null) {
                        //百度地图坐标转换成腾讯地图坐标
                        double pi = 3.141592653589793 * 3000.0 / 180.0;
                        double x = web.getLongitude() - 0.0065, y = web.getLatitude() - 0.006;
                        double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * pi);
                        double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * pi);
                        double gg_lon = z * Math.cos(theta);
                        double gg_lat = z * Math.sin(theta);
                        web.setLongitude(gg_lon);
                        web.setLatitude(gg_lat);

                        if (StringUtil.isNotEmpty(longitude) && StringUtil.isNotEmpty(latitude)) {
                            company.setDistance(GoogleMapHelper.getDistance(Double.valueOf(longitude), Double.valueOf(latitude), web.getLongitude(), web.getLatitude()));
                        }
                        company.setLatitude(web.getLatitude());
                        company.setLongitude(web.getLongitude());
                    }
                    list.add(company);
                }
            }
        }

        //重新排序并得到最新的10条记录
        if (list.size() > 0) {
            sort(list);
        }
        resultModel.setContent(list);
        return resultModel;
    }

    /**
     * 获取从F6获取所有子公司信息
     *
     * @param sendCompanys
     * @return
     */
    @Override
    public List<Company> getF6WebList(JSONArray sendCompanys, String longitude, String latitude) {
        //初始化返回值
        List<Company> list = Lists.newArrayList();


        //构筑网点信息（名称，地址，距我，经度，纬度）
        if (CollectionUtils.isNotEmpty(sendCompanys)) {
            Company company = null;
            for (int i = 0; i < sendCompanys.size(); i++) {
                JSONObject obj = sendCompanys.getJSONObject(i);
                String LONGITUDE = obj.get("LONGITUDE") + "";
                String LATITUDE = obj.get("LATITUDE") + "";
                String ADDRESS = obj.get("ADDRESS") + "";
                String KPDD = obj.get("KPDD") + "";
                String DYFHGS = obj.get("DYFHGS") + "";
                if (LONGITUDE == null || "0".equals(LONGITUDE)||"null".equals(LONGITUDE)) {
                    LONGITUDE = "";
                }

                if (LATITUDE == null || "0".equals(LATITUDE)||"null".equals(LATITUDE)) {
                    LATITUDE = "";
                }
                company = new Company();
                company.setName(KPDD);
                company.setAddress(ADDRESS);
//                company.setPhone(web.getPhone());
                if (StringUtil.isNotEmpty(LONGITUDE) && StringUtil.isNotEmpty(LATITUDE)) {
                    //百度地图坐标转换成腾讯地图坐标
                    double pi = 3.141592653589793 * 3000.0 / 180.0;
                    double x = Double.valueOf(LONGITUDE) - 0.0065, y = Double.valueOf(LATITUDE) - 0.006;
                    double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * pi);
                    double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * pi);
                    double gg_lon = z * Math.cos(theta);
                    double gg_lat = z * Math.sin(theta);
                    if (StringUtil.isNotEmpty(longitude) && StringUtil.isNotEmpty(latitude)) {
                        company.setDistance(GoogleMapHelper.getDistance(Double.valueOf(longitude), Double.valueOf(latitude), gg_lon, gg_lat));
                    }
                    company.setLatitude(gg_lat);
                    company.setLongitude(gg_lon);
                }
                list.add(company);
            }
        }

        //重新排序并得到最新的10条记录
        if (list.size() > 0) {
            sort(list);
        }

        return list;
    }

    private void sort(List<Company> list) {
        Collections.sort(list, new Comparator<Company>() {
            @Override
            public int compare(Company o1, Company o2) {
                Double distance1 = o1.getDistance();
                Double distance2 = o2.getDistance();
                if (distance1 != null && distance2 != null) {
                    if (distance1 > distance2) {
                        return 1;
                    } else if (distance1.equals(distance2)) {
                        return 0;
                    } else {
                        return -1;
                    }
                } else if (distance1 != null && distance2 == null) {
                    return -1;
                } else if (distance1 == null && distance2 != null) {
                    return 1;
                } else {
                    return -2;
                }
                //return (distance1 == null || distance2 == null) ? 9999999 : distance1.compareTo(distance2);
            }
        });
    }

    @Override
    public Company get(Company entity) {
        return null;
    }

    /**
     * 查询企业记录
     *
     * @param entity
     * @return
     */
    @Override
    public List<Company> select(Company entity) {
        return companyMapper.select(entity);
    }

    /**
     * 根据行政区划编码查询企业记录
     *
     * @param entity
     * @return
     */
    @Override
    public List<Company> getCompanyListWithOutUserId(Company entity) {
        return companyMapper.getCompanyListWithOutUserId(entity);
    }

    @Override
    @Transactional(readOnly = false)
    public ResultModel insert(Company entity) {
        ResultModel result = null;
        int r = companyMapper.insert(entity);
        if (r == 0) {
            result = ResultModel.error(ResultStatus.INSERT_ERR);
        } else {
            result = ResultModel.ok();
        }
        return result;
    }

    @Override
    public ResultModel insertSelective(Company entity) {
        return null;
    }

    @Override
    @Transactional(readOnly = false)
    public ResultModel update(Company entity) {
        ResultModel result = null;
        int r = companyMapper.updateByPrimaryKey(entity);
        if (r == 0) {
            result = new ResultModel(ResultStatus.EDIT_ERR);
        } else {
            result = ResultModel.ok();
        }
        return result;
    }

    @Override
    @Transactional(readOnly = false)
    public ResultModel updateSelective(Company entity) {
        ResultModel result = null;
        int r = companyMapper.updateByPrimaryKeySelective(entity);
        if (r == 0) {
            result = new ResultModel(ResultStatus.EDIT_ERR);
        } else {
            result = ResultModel.ok();
        }
        return result;
    }

    @Override
    @Transactional(readOnly = false)
    public ResultModel delete(Long id) {
        ResultModel result = null;
        int r = companyMapper.deleteByPrimaryKey(id);
        if (r == 0) {
            result = new ResultModel(ResultStatus.DELETE_ERR);
        } else {
            UserCompany userCompany = new UserCompany();
            userCompany.setCompanyId(id);
            userCompanyMapper.deleteByCompanyId(id);
            result = ResultModel.ok();
        }
        return result;
    }

    @Override
    public ResultModel delete(Company entity) {
        return null;
    }

    @Override
    public List<Company> findList(Company entity) {
        return companyMapper.findList(entity);
    }

    /**
     * 根据金融代码获取webUrl
     *
     * @param code
     * @return
     */
    @Override
    public String getCompanyWebUrl(String code) {
        Company company = companyMapper.selectByCode(code);
        return company.getUrl();
    }

    /**
     * 根据金融代码获取公司信息
     *
     * @param code
     * @return
     */
    @Override
    public Company getCompanyByCode(String code) {
        return companyMapper.selectByCode(code);
    }


    /**
     * 根据金融代码获取公司信息
     *
     * @param code
     * @return
     */
    @Override
    public Company queryByCompanyCode(String code) {
        Company model = companyMapper.selectByCode(code);
        TbCompany tc = null;
        //20200414 lml 改成http方式请求腾云获取公司信息
        try {
            Map<String, String> paramsNew = Maps.newHashMap();
            paramsNew.put("companyCode", model.getCode());
            paramsNew.put("passWord", MD5Util.getMD5Code(model.getTenantPass()));
            paramsNew.put("parentId", model.getId() + "");
            // 获取-腾云服务地址
            String url = IOUtils.getConfigParam("restSearchURL", "url.properties");
            String result = HttpClientUtils.post(url + "/privilegeManager/selectByParentId", paramsNew, setHeader(), 20000, 20000);
            if (result != null) {
                JSONObject j = JSON.parseObject(result);
                String object = j.get("object") + "";
                tc = JSON.parseObject(object, TbCompany.class);
            }
        } catch (Exception e) {
            System.out.println(e);
        }
        Company c = new Company();
        c.setLatitude(tc.getLatitude());
        return c;
    }

    /**
     * 获取所有公司
     *
     * @return
     */
    @Override
    public List<Company> selectAllCompanys() {
        return companyMapper.selectAllCompanys();
    }

    /*----------------------------------------------------------------------------------------------------*/

    /**
     * 从腾云服务上, 同步公司信息, 根据总公司信息
     *
     * @param model 总公司信息(code金融代码 和 tenantPass 金融密码)
     * @return
     */
    @Override
    public ResultModel synchroCompany(Company model, String loginName) {
        ResultModel rm = ResultModel.error("操作失败");
        try{
            TbCompany parent = new TbCompany();
            List<TbCompany> targetCompanyList = new ArrayList<>();

            // 1.获取-企业信息(总公司)
            rm = getParentCompany(model.getCode(), model.getTenantPass());
            if(rm.getCode() == ResultStatus.SUCCESS.getCode()){
                parent = (TbCompany) rm.getContent();
            }else{
                return rm;
            }

            // 2.获取-企业信息(子公司/网点)
            rm = getSubclassCompanys(model.getCode(), model.getTenantPass(), parent.getCompanyId().toString());
            if(rm.getCode() == ResultStatus.SUCCESS.getCode()){
                targetCompanyList = (List<TbCompany>) rm.getContent();
            }else{
                return rm;
            }

            // 3.获取-总公司信息(本项目)
            Company companyEntity = companyMapper.selectByCode(model.getCode());

            // 4.判断-公司信息-金融代码, 在本项目中是否存在
            if(companyEntity != null && StringUtil.isNotEmpty(companyEntity.getCode())){// 4.1总公司信息存在
                // 4.2.1同步-企业信息
                Map<String, Object> parentMap = BeanTransitionShopUtil.objectToMap(parent);
                Company parentModel = new Company();
                parentModel.setId(companyEntity.getId());
                parentModel.setCode(parent.getCompanyCode());
                parentModel.setTenantPass(model.getTenantPass());
                parentModel.setName(parent.getCompanyName());
                parentModel.setPhone(parent.getCompanyNameAlias() != null ? parent.getCompanyNameAlias() : parent.getCompanyName());
                parentModel.setAddress(parent.getAddressMap() != null ? parent.getAddressMap() : parent.getAddress());
                parentModel.setUpdateTime(new Date());
                companyMapper.updateByPrimaryKeySelective(parentModel);
            }else{// 4.2总公司信息不存在
                // 4.2.1同步-企业信息
                Map<String, Object> parentMap = BeanTransitionShopUtil.objectToMap(parent);
                Company parentModel = (Company)BeanTransitionShopUtil.convertMap(Company.class, parentMap);
                parentModel.setId(Long.parseLong(parent.getCompanyId().toString()));
                parentModel.setCode(parent.getCompanyCode());
                parentModel.setTenantPass(model.getTenantPass());
                parentModel.setName(parent.getCompanyName());
                parentModel.setPhone(parent.getCompanyNameAlias() != null ? parent.getCompanyNameAlias() : parent.getCompanyName());
                parentModel.setAddress(parent.getAddressMap() != null ? parent.getAddressMap() : parent.getAddress());
                parentModel.setUrl("http://f6app.feiyang56.cn:50005/WeChat.asq?");
                parentModel.setCreateTime(new Date());
                parentModel.setUpdateTime(new Date());
                companyMapper.insert(parentModel);
            }

            // 5.获取-总公司下的发货网点数
            Map<String, String> params = Maps.newHashMap();
            params.put("allCode", parent.getCompanyCode());
            Integer dgWebCount = deliverGoodsWebSetMapper.getCountByParams(params);

            // 6.判断企业信息是否存在, 存在就进行整理，并同步至数据库中
            if(targetCompanyList.size()>0){
                // 判断-子公司信息与腾云服务中不一致
//                if(targetCompanyList.size()!=dgWebCount){
                    // 6.1清理-企业信息(子公司/网点)
                    Map map = new HashMap();
                    List<String> codes = new ArrayList<>();
                    codes.add(parent.getCompanyCode());
                    map.put("companyCodes", codes);
                    map.put("updateLoginName", loginName);
                    deliverGoodsWebSetMapper.deleteByCompanyCodes(map);
                    deliverGoodsWebSetMapper.deleteByParentCodes(map);
                    // 6.2同步-子网点信息
                    List<DeliverGoodsWeb> dgwModelList = new ArrayList<>();
                    List<String> childWebNames = new ArrayList<>();
                    for(TbCompany targetCompany : targetCompanyList){
                        if(targetCompany.getDisplayFlag() != 1){
                            childWebNames.add(targetCompany.getCompanyNameAlias() != null ? targetCompany.getCompanyNameAlias() : targetCompany.getCompanyName());
                            DeliverGoodsWeb dgWeb = tbCompanyToDeliverGoodsWeb(targetCompany, parent.getCompanyCode(), true, "", loginName);
                            dgwModelList.add(dgWeb);
                        }
                    }
                    // 6.3同步-主公司-网点信息
                    DeliverGoodsWeb parentDgWeb = tbCompanyToDeliverGoodsWeb(parent, null, false, StringUtils.join(childWebNames, "|"), loginName);
                    dgwModelList.add(parentDgWeb);
                    deliverGoodsWebSetMapper.insertOnDuplicate(dgwModelList);
                    rm = ResultModel.ok();
                }else{
                    rm = ResultModel.error("当前总公司下,子公司信息与腾云服务中一致");
                }
//            }else{
//                rm = ResultModel.error("腾云服务中,当前总公司下,没有子公司信息");
//            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return rm;
    }

    /*----------------------------------------------------------------------------------------------------*/

    //[辅助方法]从认证中心获取-企业信息(总公司)
    private ResultModel getParentCompany(String companyCode, String passWord) throws Exception {
        ResultModel rm = new ResultModel();

        // 获取-腾云服务地址
        String url = IOUtils.getConfigParam("restSearchURL", "url.properties");

        Map<String, String> params = Maps.newHashMap();
        params.put("loginName", companyCode);
        params.put("password", MD5Util.getMD5Code(passWord));
        String result = HttpClientUtils.post(url + "/privilegeManager/queryCompanyByUser", params, setHeader(), 20000, 20000);
        if (result != null) {
            JSONObject j = JSON.parseObject(result);
            if("true".equals(j.get("success").toString())){
                TbCompany parent = JSON.parseObject(j.getJSONObject("object").toString(), TbCompany.class);
                rm = ResultModel.ok(parent);
            }else{
                return ResultModel.error(j.get("message").toString());
            }
        }else{
            rm = ResultModel.error("腾云服务请求失败");
        }
        return rm;
    }

    //[辅助方法]从认证中心获取-企业信息(子公司/网点)
    private ResultModel getSubclassCompanys(String companyCode, String passWord, String parentId) throws Exception {
        ResultModel rm = new ResultModel();

        // 获取-腾云服务地址
        String url = IOUtils.getConfigParam("restSearchURL", "url.properties");
        System.out.println("serverUrl:\t"+url);

        Map<String, String> params = Maps.newHashMap();
        params.put("companyCode", companyCode);
        params.put("passWord", MD5Util.getMD5Code(passWord));
        params.put("parentId", parentId);
        System.out.println("companyParams:\t"+params.toString());
        String result = HttpClientUtils.post(url + "/privilegeManager/selectByParentId", params, setHeader(), 20000, 20000);
        System.out.println("result:\t"+result);
        if(result!=null){
            JSONObject j = JSON.parseObject(result);
            if("true".equals(j.get("success").toString())){
                String  object = j.get("object").toString();
                List<TbCompany> list = JSON.parseArray(object, TbCompany.class);
                rm = ResultModel.ok(list);
            }else{
                rm = ResultModel.error(j.get("message").toString());
            }
        }else{
            rm = ResultModel.error("腾云服务请求失败");
        }
        return rm;
    }

    //[辅助方法]拼装子网点对象
    private DeliverGoodsWeb tbCompanyToDeliverGoodsWeb(TbCompany tbCompany, String parentCode, boolean isChildWeb, String childWebNames, String loginName){
        DeliverGoodsWeb deliverGoodsWeb = new DeliverGoodsWeb(
                tbCompany.getCompanyId(),
                tbCompany.getApplicationIds(),
                tbCompany.getApplicationNames(),
                tbCompany.getApplicationNamesHide(),
                tbCompany.getCompanyCode(),
                tbCompany.getCompanyName(),
                tbCompany.getParent() != null ? tbCompany.getParent().getCompanyId() : null,
                tbCompany.getParentIds(),
                tbCompany.getAddress(),
                tbCompany.getZipCode(),
                tbCompany.getLinkMan(),
                tbCompany.getPhone(),
                tbCompany.getFax(),
                tbCompany.getEmail(),
                tbCompany.getTopCompanyId(),
                tbCompany.getSysData(),
                tbCompany.getAdministrativeDivision() != null ? tbCompany.getAdministrativeDivision().getAdministrativeDivisionId() : null,
                tbCompany.getAddressMap(),
                tbCompany.getAddressDetail(),
                tbCompany.getLongitude(),
                tbCompany.getLatitude(),
                tbCompany.getWebUrl(),
                tbCompany.getActivationFlag(),
                tbCompany.getCompanyNameAlias(),
                tbCompany.getF6OrganizationCode(),
                tbCompany.getF6AccountSet(),
                tbCompany.getAuditFlag(),
                tbCompany.getAuditUser() != null ? tbCompany.getAuditUser().getUserId() : null,
                tbCompany.getAuditTime(),
                tbCompany.getAuditMessage(),
                parentCode,
                isChildWeb,
                childWebNames,
                loginName,
                loginName);
        return deliverGoodsWeb;
    }

    //[辅助方法]拼装Excel文件中的企业数据<过滤金融代码相同的数据>
    private List<Company> assembleExcelCompany(List<List<Object>> valList){
        List<String> codeList = new ArrayList<>();
        List<Company> productList = new ArrayList<>();
        for (int i=0; i<valList.size(); i++) {
            if(i==111){
                System.out.println("sss");
            }
            List<Object> val = valList.get(i);
            if (val.size() > 1) {
                Company model = new Company();
                model.setCode(val.get(0).toString().trim());//金融代码
                model.setTenantPass(val.get(1).toString().trim());//金融密码
                if(!codeList.contains(model.getCode())){
                    codeList.add(model.getCode());
                    productList.add(model);
                }
            }
        }
        return productList;
    }

    /*----------------------------------------------------------------------------------------------------*/

    @Override
    public ResultModel synchroCompanyBatch(String fileUrl, String loginName) {
        ResultModel rm = ResultModel.error("操作失败");
        try {
            //成功_条数
            int success_num = 0;

            //[读取]Excel文件内容，根据文件路径
            List<List<Object>> valList = ExcelUtil.readXlsFileByPath(fileUrl);
            List<Company> companyList = assembleExcelCompany(valList);
            for (Company companyModel : companyList){
                //同步企业数据
                ResultModel rmItem = synchroCompany(companyModel, loginName);
                if(rmItem.getCode() == ResultStatus.SUCCESS.getCode()){
                    success_num += 1;
                }
            }
            rm = ResultModel.ok();
            rm.setMsg("操作成功, 同步"+success_num+"家企业的信息!");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return rm;
    }


    /*----------------------------------------------------------------------------------------------------*/

    /**
     * 获取全部物流企业
     *
     * @return
     */
    @Override
    public List<Company> selectCompanyList(Company entity) {
        return companyMapper.selectCompanyList(entity);
    }

    public TbCompany deliverGoodsWebToTbCompany(DeliverGoodsWeb deliverGoodsWeb) {
        TbCompany tbCompany = new TbCompany();
        tbCompany.setCompanyId(deliverGoodsWeb.getCompanyId());
        tbCompany.setApplicationIds(deliverGoodsWeb.getApplicationIds());
        tbCompany.setApplicationNames(deliverGoodsWeb.getApplicationNames());
        tbCompany.setApplicationNamesHide(deliverGoodsWeb.getApplicationNamesHide());
        tbCompany.setCompanyCode(deliverGoodsWeb.getCompanyCode());
        tbCompany.setCompanyName(deliverGoodsWeb.getCompanyName());
        tbCompany.setParentIds(deliverGoodsWeb.getParentIds());
        tbCompany.setAddress(deliverGoodsWeb.getAddress());
        tbCompany.setZipCode(deliverGoodsWeb.getZipCode());
        tbCompany.setLinkMan(deliverGoodsWeb.getLinkMan());
        tbCompany.setPhone(deliverGoodsWeb.getPhone());
        tbCompany.setFax(deliverGoodsWeb.getFax());
        tbCompany.setEmail(deliverGoodsWeb.getEmail());
        tbCompany.setTopCompanyId(deliverGoodsWeb.getTopCompanyId());
        tbCompany.setSysData(deliverGoodsWeb.getSysData());
        tbCompany.setAddressMap(deliverGoodsWeb.getAddressMap());
        tbCompany.setAddressDetail(deliverGoodsWeb.getAddressDetail());
        tbCompany.setLongitude(deliverGoodsWeb.getLongitude());
        tbCompany.setLatitude(deliverGoodsWeb.getLatitude());
        tbCompany.setWebUrl(deliverGoodsWeb.getWebUrl());
        tbCompany.setActivationFlag(deliverGoodsWeb.getActivationFlag());
        tbCompany.setCompanyNameAlias(deliverGoodsWeb.getCompanyNameAlias());
        tbCompany.setF6OrganizationCode(deliverGoodsWeb.getF6OrganizationCode());
        tbCompany.setF6AccountSet(deliverGoodsWeb.getF6AccountSet());
        tbCompany.setAuditFlag(deliverGoodsWeb.getAuditFlag());
        tbCompany.setAuditTime(deliverGoodsWeb.getAuditTime());
        tbCompany.setAuditMessage(deliverGoodsWeb.getAuditMessage());
        tbCompany.setDisplayFlag(0);
        return tbCompany;
    }
}
